<?php

namespace plugin\admin\app\common\alibabacloud\real_name_auth;

use plugin\admin\app\service\v1\OptionService;
use support\Log;

class Api
{

    public static function createClient($function = 'ident')
    {
        $config = OptionService::getConfig();
        return $config[$function];
    }

    /**
     * 手机三要素实名认证
     *
     * @param string $mobile
     * @param string $idCard
     * @param string $realName
     */
    public static function mobilethree($mobile, $idCard, $realName)
    {
        $data = compact('mobile', 'idCard', 'realName');

        $msg = '【手机三要素实名认证】 ';
        $config = self::createClient();
        if (empty($config['appcode'])) {
            return V(1, $msg . '缺少APPCODE配置');
        }

        $log = Log::channel('real_name_auth');
        $log->info($msg . 'request ', $data);

        $host = "https://zpc.market.alicloudapi.com";
        $path = "/efficient/cellphone/post";
        $method = "POST";
        $appcode = $config['appcode'];
        $headers = [
            'Authorization: APPCODE ' . $appcode,
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
        ];
        $postData = http_build_query($data);
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        // 执行请求并获取响应
        $response = curl_exec($curl);
        // 检查错误
        if (curl_errno($curl)) {
            return V(1, $msg . '请求错误: ' . curl_error($curl));
        }
        // 关闭cURL资源
        curl_close($curl);

        $result = json_decode($response, true);
        $log->info($msg . 'data ', $result);
        if ($result['error_code'] == 0) {
            switch ($result['result']['VerificationResult']) {
                case '0':
//                    return V(1, $msg . $result['reason']);
                    return V(1, $msg . '系统无记录');
                    break;
                case '-1':
//                    return V(1, $msg . $result['reason']);
                    return V(1, $msg . '信息不匹配');
                    break;
                case '1':
                    return V(0, '信息匹配', $result);
                    break;
            }
        }
        return V(1, $msg . $result['reason']);
    }
}